package com.itheima.tlias84.Interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.entity.Emp;
import com.itheima.tlias84.mapper.EmpMapper;
import com.itheima.tlias84.utils.JwtUtils;
import com.itheima.tlias84.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录拦截器 连接器由Spring提供
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    EmpMapper empMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("开始执行http请求拦截");
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否有token->是否绕过登录
        if(Objects.isNull(token)){
            writeErrorResponse(response,"请先登录");
            return false;
        }
        //使用jwt验证token
        //验证token合法性
        try {
            JSONObject jsonObject = JwtUtils.verifyToken(token);
            Emp emp = empMapper.selectEmpByUsername(jsonObject.getString("username"));
            if (Objects.isNull(emp)||!emp.getPassword().equals(jsonObject.getString("password"))){
                writeErrorResponse(response,"token不合法或者过期");
                return false;
            }
        }catch (Exception e){
            writeErrorResponse(response,"token不合法或者过期");
            return false;
        }
        log.info("拦截完成");
        return true;
    }
    private static void writeErrorResponse(HttpServletResponse servletResponse, String msg) throws IOException {
        //设置UTF-8编码
        servletResponse.setContentType("application/json;charset=UTF-8");
        servletResponse.setCharacterEncoding("UTF-8");
        //设置响应状态码
        servletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        PrintWriter writer = servletResponse.getWriter();
        ResultUtil fail = ResultUtil.fail(msg);
        //使用fastjson把对象转成json字符串
        writer.write(JSONObject.toJSONString(fail));
    }
}
